﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.IO;
using System.Reflection;

namespace Dukou.Javascript
{
    public class Js : JsBase, IDisposable
    {
        public Js(HtmlHelper htmlHelper) 
            : base(htmlHelper)
        {
            this.Writer.Write("<script2 type=\"text/javascript\">");
            this.Writer.WriteLine();
        }

        public Js(HtmlHelper htmlHelper, string src)
            : this(htmlHelper)
        {
            this.Writer.Write(string.Format("<script type=\"text/javascript\" src=\"{0}\">", src));
        }

        public void Assign(JsVar left, object right)
        {
            Assign(left, JsValue.Create(right));
        }

        public void Assign(JsVar left, JsValue right)
        {
            this.Writer.WriteLine(string.Format("{0} = {1};", left.Name, right));
        }

        public void Assign(JsVar left, JsVar right)
        {
            this.Writer.WriteLine(string.Format("{0} = {1};", left.Name, right.Name));
        }

        public void Assign(JsVar left, JsExpr right)
        {
            this.Writer.WriteLine(string.Format("{0} = {1}", left.Name, right));
        }

        public JsVar Var(string name)
        {
            return Var(name, JsValue.Create(null));
        }

        public JsVar Var(string name, object right)
        {
            return Var(name, JsValue.Create(right));
        }

        public JsVar Var(string name, JsValue right)
        {
            JsVar var = new JsVar(name) { Value = right };
            this.Writer.WriteLine(string.Format("var {0} = {1};", var.Name, var.Value));
            return var;
        }

        public JsVar Var(string name, JsVar right)
        {
            JsVar var = new JsVar(name) { Value = JsValue.Create(right.Value) };
            this.Writer.WriteLine(string.Format("var {0} = {1};", var.Name, right.Name));
            return var;
        }

        public JsVar Var(string name, JsExpr right)
        {
            JsVar var = new JsVar(name) { Value = null };
            this.Writer.WriteLine(string.Format("var {0} = {1}", var.Name, right));
            return var;
        }

        public JsIf if_(JsExpr expr) 
        {
            return new JsIf(this.HtmlHelper, expr);
        }

        public JsElseIf else_if(JsExpr expr)
        {
            return new JsElseIf(this.HtmlHelper, expr);
        }

        public JsElse else_()
        {
            return new JsElse(this.HtmlHelper);
        }

        public void Dispose()
        {
            this.Writer.Write("</script2>");
        }
    }
}
